<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="考生号" prop="ksh">
        <el-input v-model="queryParams.ksh" placeholder="请输入考生号" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="到达车站" prop="atStation">
        <el-input v-model="queryParams.atStation" placeholder="请输入到达车站" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="到达时间" prop="atDatetime">
        <el-date-picker clearable v-model="queryParams.atDatetime" type="date" value-format="yyyy-MM-dd"
          placeholder="请选择到达时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="是否接站" prop="isNeedPick">
        <el-input v-model="queryParams.isNeedPick" placeholder="请输入是否接站" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="是否被接" prop="pickState">
        <el-input v-model="queryParams.pickState" placeholder="请输入是否被接" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="班级" prop="classId">
        <el-cascader v-model="class_cas" ref="cas" style="width: 500px;" :options="cascaderData"
          :props="{ checkStrictly: false }" @change="handleChange" clearable filterable></el-cascader>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['stureg:station:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['stureg:station:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['stureg:station:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['stureg:station:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="stationList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="id" align="center" prop="id" />
      <el-table-column label="考生号" align="center" prop="ksh" />
      <el-table-column label="班级" align="center" prop="className" />
      <el-table-column label="学生姓名" align="center" prop="name" />
      <el-table-column label="交通工具" align="center">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.vehicle_types" :value="scope.row.toolsType" />
        </template>
      </el-table-column>
      <el-table-column label="到达车站" align="center" prop="atStation" />
      <el-table-column label="到达时间" align="center" prop="atDatetime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.atDatetime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="是否需要接站" align="center">
        <template slot-scope="scope">
          {{ scope.row.isNeedPick == "1" ? "是" : "否" }}
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['stureg:station:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['stureg:station:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改新生接站登记对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="考生号" prop="ksh">
          <el-input v-model="form.ksh" placeholder="请输入考生号" />
        </el-form-item>
        <el-form-item label="学生id" prop="studentId">
          <el-input v-model="form.studentId" placeholder="请输入学生id" />
        </el-form-item>
        <el-form-item label="到达车站" prop="atStation">
          <el-input v-model="form.atStation" placeholder="请输入到达车站" />
        </el-form-item>
        <el-form-item label="到达时间" prop="atDatetime">
          <el-date-picker clearable v-model="form.atDate" type="date" value-format="yyyy-MM-dd" placeholder="请选择到达时间">
          </el-date-picker>
          <el-time-picker v-model="form.atTime" :picker-options="{ selectableRange: '00:00:00 - 23:59:59' }"
            placeholder="任意时间点"></el-time-picker>
        </el-form-item>
        <el-form-item label="是否接站" prop="isNeedPick">
          <el-input v-model="form.isNeedPick" placeholder="请输入是否接站" />
        </el-form-item>
        <el-form-item label="是否被接" prop="pickState">
          <el-input v-model="form.pickState" placeholder="请输入是否被接" />
        </el-form-item>
        <el-form-item label="删除标志" prop="delFlag">
          <el-input v-model="form.delFlag" placeholder="请输入删除标志" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listStation, getStation, delStation, addStation, updateStation } from "@/api/stureg/station";
import { treeStudent } from "@/api/stuCQS/basedata/student";
export default {
  name: "Station",
  dicts: ['vehicle_types'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 新生接站登记表格数据
      stationList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        ksh: null,
        studentId: null,
        toolsType: null,
        atStation: null,
        atDatetime: null,
        isNeedPick: null,
        pickState: null,
        status: null,
        className: null,
        classId: null

      },
      // 表单参数
      form: {
        atTime: null,
        atDate: null
      },
      // 表单校验
      rules: {
      },
      class_cas: [],
      cascaderData: null,
    };
  },
  created() {
    this.getList();
    this.getCascaderData();
  },
  methods: {
    /** 查询新生接站登记列表 */
    getList() {
      this.loading = true;
      console.log('正在请求的数据:', this.queryParams);
      listStation(this.queryParams).then(response => {
        this.stationList = response.rows
        console.log(this.stationList);
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        ksh: null,
        studentId: null,
        toolsType: null,
        atStation: null,
        atDatetime: null,
        isNeedPick: null,
        pickState: null,
        status: null,
        delFlag: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        className: null,
        classId: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
      this.class_cas = [];
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加新生接站登记";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getStation(id).then(response => {
        const data = response.data;

        // 处理 atDatetime，将其拆分为 atDate 和 atTime
        if (data.atDatetime) {
          const [datePart, timePart] = data.atDatetime.split(' ');

          // 设置表单字段
          this.form.atDate = datePart; // 格式: yyyy-MM-dd
          // this.form.atTime = timePart; // 格式: HH:mm:ss
        } else {
          this.form.atDate = null;
          // this.form.atTime = null;
        }

        // 其他字段赋值
        this.form = {
          ...this.form,
          ...data
        };

        this.open = true;
        this.title = "修改新生接站登记";
        console.log(this.form);
      });
    },
    format(date, type) {
      let yy = new Date(date).getFullYear()
      let MM = this.addZero(new Date(date).getMonth() + 1)
      let dd = this.addZero(new Date(date).getDate())
      let HH = this.addZero(new Date(date).getHours())
      let mm = this.addZero(new Date(date).getMinutes())
      let ss = this.addZero(new Date(date).getSeconds())
      if (type === 'yy') {
        return yy.toString()
      } else if (type === 'yy-MM-dd HH:mm:ss') {
        return yy + '-' + MM + '-' + dd + ' ' + HH + ':' + mm + ':' + ss
      }
    },
    addZero(data) {
      if (data < 10) {
        return '0' + data
      } else {
        return data
      }
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          const date = this.form.atDate;
          const time = this.form.atTime;
          if (date && time) {
            const formattedDate = new Date(date).toISOString().split('T')[0]; // 获取 YYYY-MM-DD 部分
            const formattedTime = time instanceof Date
              ? this.addZero(time.getHours()) + ':' + this.addZero(time.getMinutes()) + ':00'
              : this.addZero(time.getHours()) + ':' + this.addZero(time.getMinutes()) + ':00';

            this.form.atDatetime = `${formattedDate} ${formattedTime}`;
          } else {
            this.form.atDatetime = null;
          }


          if (this.form.id != null) {
            // 拼接日期和时间
            updateStation(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList(); console.log(this.form)
            });
          } else {
            addStation(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除新生接站登记编号为"' + ids + '"的数据项？').then(function () {
        return delStation(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('stureg/pickstation/export', {
        ...this.queryParams
      }, `station_${new Date().getTime()}.xlsx`)
    },
    handleChange(value) {
      // 更新查询参数中的班级信息

      this.queryParams.classId = value[2];
      // 重新查询数据
      this.handleQuery();
    },
    // 级联选择数据
    async getCascaderData() {
      const res = await treeStudent()
      this.cascaderData = res.data
      this.cascaderData.forEach(dept => {
        dept.children.forEach(major => {
          major.children.forEach(c => {
            delete c.children
          })
        })
      });
    },
  }
};
</script>
